package com.haoqizhe.kernel.web.handler;

import com.haoqizhe.kernel.web.result.DefaultErrorResult;
import com.haoqizhe.kernel.annotation.ResponseResult;
import com.haoqizhe.kernel.commons.util.RequestContextUtil;
import com.haoqizhe.kernel.interceptor.ResponseResultInterceptor;
import com.haoqizhe.kernel.web.result.IResult;
import com.haoqizhe.kernel.web.result.Result;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * 接口响应体处理器
 *
 * @author haoqizhe.li
 * @date 2018/4/2 23:27
 */
@ControllerAdvice
public class ResponseResultHandler implements ResponseBodyAdvice<Object> {
    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        ResponseResult responseResultAnn = (ResponseResult) RequestContextUtil.getRequest().getAttribute(ResponseResultInterceptor.RESPONSE_RESULT);
        return responseResultAnn == null ? false : true;
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        ResponseResult responseResultAnn = (ResponseResult) RequestContextUtil.getRequest().getAttribute(ResponseResultInterceptor.RESPONSE_RESULT);

        Class<? extends IResult> resultClazz = responseResultAnn.value();

        if (resultClazz.isAssignableFrom(Result.class)) {
            if (body instanceof DefaultErrorResult) {
                DefaultErrorResult defaultErrorResult = (DefaultErrorResult) body;
                return defaultErrorResult;
            } else if (body instanceof Result) {
                return body;
            }

            return Result.success(body);
        }

        return body;
    }
}
